package io.hellsinger.filesystem.attribute.time

import java.text.SimpleDateFormat
import java.util.Locale

class PathTime(
    val seconds: Long,
    val nanos: Long,
) : Comparable<PathTime> {
    fun toStringWithLocale(locale: Locale): String {
        val current =
            java.util.GregorianCalendar().apply {
                timeInMillis = System.currentTimeMillis()
            }
        val stamp =
            java.util.GregorianCalendar().apply {
                timeInMillis = toEpochMilli()
            }
        val pattern = if (stamp.time.year == current.time.year) "d MMM" else "d MMM y"

        return SimpleDateFormat(pattern, locale).format(toEpochMilli())
    }

    private fun toEpochMilli(): Long = (seconds * 1000) + (nanos / 1000_000)

    override fun compareTo(other: PathTime): Int = other.nanos.compareTo(nanos) + other.seconds.compareTo(seconds)

    override fun toString(): String {
        val current =
            java.util.GregorianCalendar().apply {
                timeInMillis = System.currentTimeMillis()
            }
        val stamp =
            java.util.GregorianCalendar().apply {
                timeInMillis = toEpochMilli()
            }
        val pattern = if (stamp.time.year == current.time.year) "d MMM" else "d MMM y"

        return SimpleDateFormat(pattern).format(toEpochMilli())
    }
}
